package admincontroller

import (
	"context"
	"encoding/json"
	"vpn-management-server/logger"
	"vpn-management-server/network"
	"vpn-management-server/security/code"
	"vpn-management-server/src/dao/admindao"
	"vpn-management-server/src/dao/ugroupdao"
	"vpn-management-server/src/model/adminmodel"
	"vpn-management-server/src/service/adminservice"
	"vpn-management-server/src/service/authservice"
)

func AddAdmin(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	// 转换类型
	if admin, ok := request.GetModel().(*adminmodel.Admin); ok {
		adminservice.AddAdminService(ctx, admin, response)
	} else {
		// TODO 转换失败 回送信息
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "Transform interface to AdminUserJson fail")
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "transform interface to AdminUserJson fail"
	}
}

func DeleteAdminByID(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	// 转换类型
	if adminNameInfo, ok := request.GetModel().(*adminmodel.AdminNameInfo); ok {
		if ok := admindao.HasAdminByID(adminNameInfo.ID); ok {
			err := admindao.DeleteAdmin(adminNameInfo.ID)
			if err != nil {
				logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "add dao fail,err", err)
				response.Code = code.BAD_REQUEST
				response.ErrorMsg = "delete admin fail"
				return
			}
			response.Code = code.SUCCESS
			logger.Logger.Infof("delete admin %s success\n", adminNameInfo.Name)
		} else {
			logger.Logger.Errorf("admin %s is not existed\n", adminNameInfo.Name)
			response.Code = code.NOT_FOUND
			response.ErrorMsg = "admin is not existed"
		}
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "Transform interface to AdminUserJson fail")
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "transform interface to AdminNameJson fail"
	}
}

func GetAllAdmins(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	AdminUsers := admindao.GetAllAdmins()
	if AdminUsers == nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "get admin fail")
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "get admins info fail"
		return
	}
	data, _ := json.Marshal(AdminUsers)
	response.Code = code.SUCCESS
	response.Data = data
	logger.Logger.Infof("get admins info success\n")
}

func GetCurrAdmin(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	admin := adminservice.GetCurrAdminService(ctx, request, response)
	if admin == nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "get admin fail, the admin is not existed")
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "get admin info fail, the admin is not existed"
		return
	}
	data, _ := json.Marshal(admin)
	response.Code = code.SUCCESS
	response.Data = data
	logger.Logger.Infof("get admin %s info success\n", admin.Name)
}

func AddUGroupAdmin(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	if UGroupAdmin, ok := request.GetModel().(*adminmodel.UGroupAdmin); ok {
		if ugroupdao.HasUGroupByID(UGroupAdmin.UGroupID) {
			id := int(adminservice.AddAdminService(ctx, &UGroupAdmin.Admin, response))
			if response.Code == code.SUCCESS && id != -1 {
				// 跟据前端传过来的用户组ID和本地创建管理员得到的管理员ID 更新用户组状态
				if err := ugroupdao.UpdateUGroupWithAdminID(UGroupAdmin.UGroupID, id); err != nil {
					// TODO 出现错误删除添加的管理员
					adminUserJson := &adminmodel.AdminNameInfo{
						ID:   id,
						Name: UGroupAdmin.Name,
					}
					_ = admindao.DeleteAdmin(adminUserJson.ID)
					logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "add ugroup admin fail, the err is"+err.Error())
					response.Code = code.BAD_REQUEST
					response.ErrorMsg = "add ugroup admin fail"
					return
				}
				response.Code = code.SUCCESS
				logger.Logger.Info("add ugroup admin success")
			}
		} else {
			logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "add ugroup admin fail, user group is not existed:", UGroupAdmin.UGroupID)
			response.Code = code.NOT_FOUND
			response.ErrorMsg = "add ugroup admin fail,User group is not existed"
			return
		}

	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "Transform interface to AdminUserJson fail")
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "transform interface to UGroupAdminJson fail"
	}
}

func Login(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	if adminLogin, ok := request.GetModel().(*adminmodel.AdminLogin); ok {
		if admin, ok := admindao.GetAdminByName(adminLogin.Name); ok {
			if admin.Password == adminLogin.Password {
				// 密码一致 登录成功
				authservice.SetSession(ctx, admin, response)
				response.Code = code.SUCCESS
				data, _ := json.Marshal(admin)
				response.Data = data
				logger.Logger.Infof("admin %s login success\n", admin.Name)
			} else {
				response.Code = code.UNAUTHORIZED
				response.ErrorMsg = "wrong password"
				logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "wrong password")
			}
		} else {
			logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "the admin is not existed")
			response.Code = code.UNAUTHORIZED
			response.ErrorMsg = "admin not exist"
			return
		}
	}
}

func Reset(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	if adminReset, ok := request.GetModel().(*adminmodel.AdminReset); ok {
		if admin, ok := admindao.GetAdminByName(adminReset.Name); ok {
			if admin.Password == adminReset.OldPassword {
				// 密码一致 修改密码
				if err := admindao.UpdateAdminByName(adminReset.NewPassword, adminReset.Name, adminReset.TimeStamp); err != nil {
					logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "update admin password fail", err)
					response.Code = code.BAD_REQUEST
					response.ErrorMsg = "update admin password fail"
					return
				}
				response.Code = 200
				logger.Logger.Infof("admin %s reset success\n", admin.Name)
			} else {
				response.Code = code.UNAUTHORIZED
				response.ErrorMsg = "wrong password"
				logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "wrong password")
			}
		} else {
			logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "get admin fail, the admin is not existed")
			response.Code = code.BAD_REQUEST
			response.ErrorMsg = "get admin info fail, the admin is not existed"
			return
		}
	}
}
